package edu.hawaii.webspider;

/**
 * Runs a WebSpider.
 * 
 * @author Marcius Bagwan
 */
public class WebSpiderExample {
  /** Holds arguments from the command line. */
  String[] commandLineArguments;
  
  /**
   * A WebSpider Example demonstrates how the WebSpider class is used.
   * 
   * @param args The command line arguments.
   */
  WebSpiderExample(String[] args) {
    this.commandLineArguments = args;
  }
  
  /**
   * Retrieves a home page specified on the command-line and counts the number of links on it.
   * 
   * @param args Ignored.
   * @throws Exception If problems occur.
   */
  public static void main(String[] args) throws Exception {
    WebSpiderExample webSpiderExample = new WebSpiderExample(args);
    webSpiderExample.runWebSpider();
  }
  
  /**
   * Processes arguments in the command line and runs a WebSpider.
   * @throws Exception If a bad URL is given.
   */
  public void runWebSpider() throws Exception {
    /** Keeps track of arguments used in the command line. */
    String totalLinks = "-totallinks";
    String mostPopular = "-mostpopular";
    String logging = "-logging";    
    boolean totalLinksFlag = false;
    boolean mostPopularFlag = false;
    boolean loggingFlag = false;
    
    int commandLineMaxPages = 0;
    String commandLineUrl = "";

    for (String commandLineArgs : this.commandLineArguments) {
      if (commandLineArgs.equals(totalLinks)) {
        totalLinksFlag = true;
      }
      else if (commandLineArgs.equals(mostPopular)) {
        mostPopularFlag = true;
      }
      else if (commandLineArgs.equals(logging)) {
        loggingFlag = true;
      }
      else if (!commandLineArgs.substring(0, 0).equals("-")) {

        try {
          commandLineMaxPages = Integer.parseInt(commandLineArgs);
        }
        catch (NumberFormatException maxPageCheck) {
          commandLineUrl = commandLineArgs;
          continue;
        }
      }
    }
    commandLineUrl = "http://www.hackystat.org";
    commandLineMaxPages = 3;

    WebSpider webSpider = new WebSpider(commandLineUrl, commandLineMaxPages);
    
    System.out.println("The provided link, "
        + webSpider.getUrl()
        + ", contains "
        + webSpider.getLinks(commandLineUrl) + " links.");
        //+ webSpider.getLinkStats(commandLineUrl, commandLineMaxPages) + " links.");
    
  }

}